package internal

import (
	"BJXM_Shooting/msg"
	"fmt"
	"github.com/name5566/leaf/gate"
	"github.com/name5566/leaf/log"
	"math/rand"
	"sync"
	"time"
)

var (
	// 正在匹配的人
	matchingUsers = struct {
		sync.RWMutex
		data map[string]*User
	}{data: make(map[string]*User)}

	// 通知匹配找人
	joinMatching   = make(chan *User, 0)
	deleteMatching = make(chan string, 0)
)

func init() {
	handler(&msg.C2S_Matching{}, handlerMatching)
	go matchingWork()

	// 查看成员状态
	//go func() {
	//	for {
	//		log.Debug("总人数:%d 匹配人数:%d", len(users.data), len(matchingUsers.data))
	//		for _, v := range users.data {
	//			log.Debug("昵称:%s 索引:%d", v.data.Account, v.index)
	//		}
	//
	//		time.Sleep(1 * time.Second)
	//	}
	//
	//}()
	rand.Seed(time.Now().Unix())
}

// 处理玩家匹配消息
func handlerMatching(args []interface{}) {
	info := args[0].(*msg.C2S_Matching)
	agentObj := args[1].(gate.Agent)

	user := agentObj.UserData().(*User)
	fmt.Println(user)
	if user.data == nil || !user.auth {
		agentObj.WriteMsg(&msg.S2C_MatchingError{
			ID:  msg.S2C_ID_InnerError,
			Msg: "账户未登录",
		})
		agentObj.Close()
		return
	}
	log.Release("[加入匹配]昵称:%s\n", user.data.Nickname)
	// 启动一个线程处理
	skeleton.Go(func() {
		// 设置玩家身上的匹配状态
		user.matching = info
	}, func() {
		user.state = stateMatching
		// 加入到匹配map中
		matchingUsers.Lock()
		matchingUsers.data[user.data.Account] = user
		matchingUsers.Unlock()
		joinMatching <- user

	})
}

// 匹配工作池
// 实现思路:当有人进来的时候才遍历一次
func matchingWork() {
	// 用channel通知是否有新的用户进来,然后遍历检测匹配玩家
	for {
		select {
		case join := <-joinMatching:
			// 遍历查找匹配玩家
			matchingUsers.Lock()
			for _, player := range matchingUsers.data {
				// 如果是自己则跳过
				if join.data.Account == player.data.Account {
					continue
				}
				// 检测是否想匹配
				// 1.玩家状态 2.匹配ID 3.匹配分场
				if player.state == stateMatching &&
					(join.matching.ID == player.matching.ID &&
						join.matching.Score == player.matching.Score) {

					player1 := join
					player2 := player
					skeleton.Go(func() {
						// 创建战斗房间
						info := createBattleRoom(player1, player2)
						player1.WriteMsg(&info)
						player2.WriteMsg(&info)

					}, func() {
						// 从匹配map中删除成员
						matchingUsers.Lock()
						delete(matchingUsers.data, player1.data.Account)
						delete(matchingUsers.data, player2.data.Account)
						matchingUsers.Unlock()
					})
					break
				}
			}
			matchingUsers.Unlock()
		case del := <-deleteMatching:
			// 从匹配map中删除成员
			matchingUsers.Lock()
			delete(matchingUsers.data, del)
			delete(matchingUsers.data, del)
			matchingUsers.Unlock()
		}
	}
}
